package com.example.entity;

import com.fasterxml.jackson.annotation.JsonIgnore;
import jakarta.persistence.*;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.time.LocalDateTime;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 系统管理员实体
 */
@Data
@EqualsAndHashCode(callSuper = true)
@Entity
@Table(name = "admins")
public class Admin extends BaseEntity implements UserDetails {

    @Column(unique = true, nullable = false, length = 50)
    private String username;

    @Column(unique = true, nullable = false, length = 20)
    private String phone;

    @JsonIgnore
    @Column(nullable = false)
    private String password;

    @Column(name = "real_name", nullable = false, length = 50)
    private String realName;

    @Column(length = 100)
    private String email;

    @Column(length = 255)
    private String avatar;

    @Enumerated(EnumType.STRING)
    @Column(nullable = false)
    private AdminRole role = AdminRole.ADMIN;

    @Column(columnDefinition = "JSON")
    private String permissions;

    @Enumerated(EnumType.STRING)
    @Column(nullable = false)
    private AdminStatus status = AdminStatus.ACTIVE;

    @Column(name = "last_login_time")
    private LocalDateTime lastLoginTime;

    @Column(name = "last_login_ip", length = 50)
    private String lastLoginIp;

    // 权限枚举
    public enum AdminRole {
        SUPER_ADMIN("超级管理员"),
        ADMIN("管理员"),
        OPERATOR("操作员");

        private final String description;

        AdminRole(String description) {
            this.description = description;
        }

        public String getDescription() {
            return description;
        }
    }

    // 状态枚举
    public enum AdminStatus {
        ACTIVE("正常"),
        INACTIVE("禁用");

        private final String description;

        AdminStatus(String description) {
            this.description = description;
        }

        public String getDescription() {
            return description;
        }
    }

    // Spring Security UserDetails 接口实现
    @Override
    @JsonIgnore
    public Collection<? extends GrantedAuthority> getAuthorities() {
        // 基于角色的权限
        return List.of(new SimpleGrantedAuthority("ROLE_" + role.name()));
    }

    @Override
    @JsonIgnore
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    @JsonIgnore
    public boolean isAccountNonLocked() {
        return status == AdminStatus.ACTIVE;
    }

    @Override
    @JsonIgnore
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    @JsonIgnore
    public boolean isEnabled() {
        return status == AdminStatus.ACTIVE;
    }

    // 获取权限列表
    public List<String> getPermissionList() {
        if (permissions == null || permissions.isEmpty()) {
            return List.of();
        }
        
        try {
            // 解析JSON格式的权限字符串
            return List.of(permissions.replaceAll("[\\[\\]\"]", "").split(","))
                    .stream()
                    .map(String::trim)
                    .filter(s -> !s.isEmpty())
                    .collect(Collectors.toList());
        } catch (Exception e) {
            return List.of();
        }
    }

    // 检查是否有指定权限
    public boolean hasPermission(String permission) {
        if (role == AdminRole.SUPER_ADMIN) {
            return true; // 超级管理员拥有所有权限
        }
        return getPermissionList().contains(permission);
    }

    // 获取显示名称
    public String getDisplayName() {
        return realName != null && !realName.isEmpty() ? realName : username;
    }
}
